import pgzrun
import random, time, json

with open('world.json', 'r')as f:
	ft = f.read()
	world = json.loads(ft)
	next_world = json.loads(ft)
ROWS = len(world)
COLS = len(world[0])

CELL_SIZE = 15

HEIGHT = (ROWS * CELL_SIZE)
WIDTH  = (COLS * CELL_SIZE)

BACK_COLOR = (0, 0, 127)
CELL_COLOR = (0, 200, 0)


def random_map(w):
	for r in range(ROWS):
		for c in range(COLS):
			w[r][c] = int(random.randint(0, 7) == 0)

def draw_cell(r, c):
	cx = CELL_SIZE * c
	cy = CELL_SIZE * r
	cell_rect = Rect((cx, cy), (CELL_SIZE, CELL_SIZE))
	screen.draw.filled_rect(cell_rect, CELL_COLOR)

def count_neighbors(w, r, c):
	sums = 0
	for nr in range(r - 1, r + 1 + 1):
		for nc in range(c - 1, c + 1 + 1):
			if nr == r and nc == c:
				if w[1][1]:
					sums += 1
					continue
			
			if nr >= r:
				if w[1][nc-1]:
					sums += 1
					continue
			
			if nc >= c:
				if w[nr-1][1]:
					sums += 1
					continue

			if nr <= 0 and nc <= 0:
				if w[r-1][c-1]:
					sums += 1
					continue
			
			if nr <= 0:
				if w[r-1][nc-1]:
					sums += 1
					continue
			
			if nc <= 0:
				if w[nr-1][c-1]:
					sums += 1
					continue

			if w[nr-1][nc-1]:
				sums += 1

	return sums

def next_cell(w, r, c):
	n = count_neighbors(w, r, c)

	if n == 3:
		return 1
	elif n == 2:
		return w[r][c]
	else:
		return 0


def update():
	for r in range(ROWS):
		for c in range(COLS):
			next_world[r][c] = next_cell(world, r, c)
	
	for r in range(ROWS):
		for c in range(COLS):
			world[r][c] = next_world[r][c]
	time.sleep(0.5)

def draw():
	screen.fill(BACK_COLOR)
	for r in range(ROWS):
		for c in range(COLS):
			if world[r][c]:
				draw_cell(r, c)

random_map(world)

pgzrun.go()
